package com.cn.why.springcloudskills.FaceTest;

import java.util.concurrent.CountDownLatch;

/**
 * 构建一个线程安全的单例
 */
public class MysigleThread {
    //双重锁的单例
    private static volatile MysigleThread sigleThread;
    public static int index = 0;
    //私有构造器，防止被外部实例化
    private MysigleThread(){
        ++index;
    }
    public static MysigleThread getSigle(){
        if(sigleThread == null){
            //锁住该单例
            synchronized (MysigleThread.class){
                //双重判断
                if(sigleThread == null){
                    sigleThread = new MysigleThread();
                    System.out.println(index);
                }
            }
        }
        return sigleThread;
    }

    public static void main(String[] args) throws Exception{
        //压力测试(10个线程)
        CountDownLatch latch = new CountDownLatch(1000);
        for (int a = 0;a <1000;a++){
            new Runnable() {
                @Override
                public void run() {
                    //每个线程都去获取该单例
                    MysigleThread.getSigle();
                    latch.countDown();
                }
            }.run();
        }
        latch.await();
    }
}
